package com.leonwoodstudio.endorsementclient;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class MainService extends Service {
    Thread server_thread;
    Handler handler;
    String local_port;
    public static final int MSG_RECV_XML = 0;
    public static final int MSG_RECV_PIC = 1;
    public static final int MSG_RECV_FAIL = 2;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        local_port = intent.getStringExtra("local_port");
        if (server_thread == null) {
            server_thread = new ServerSocketThread(Integer.valueOf(local_port), handler);
            server_thread.start();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler() {
            public void handleMessage(Message msg) {// 此方法在ui线程运行
                switch (msg.what) {
                    case MSG_RECV_XML:
                    case MSG_RECV_PIC:
                        sendFileReceivedBroadcast(msg.what, (String)msg.obj);
                        break;
                    case MSG_RECV_FAIL:
                        sendFileReceivedBroadcast(msg.what, null);
                        break;
                }
            }
        };
    }

    public void sendFileReceivedBroadcast(int type, String file) {
        Intent intent=new Intent();
        intent.setAction(Util.ACTION_FILE_RECEIVED);
        intent.putExtra("type", type);
        intent.putExtra("file", file);
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
